package com.kashow.base.rx.dialog;

import android.content.Context;

import java.lang.ref.WeakReference;

import rx.Subscriber;


public abstract class ProgressSubscriber<T> extends Subscriber<T> implements ProgressCancelListener{
    private WeakReference<Context> mContext;
    private ProgressDialogHandler mHandler;

    public ProgressSubscriber(WeakReference<Context> context){
        mContext = context;
        mHandler = new ProgressDialogHandler(context,this,true);
    }

    private void showProgressDialog(){
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.SHOW_PROGRESS_DIALOG).sendToTarget();
        }
    }

    private void dismissProgressDialog(){
        if (mHandler != null) {
            mHandler.obtainMessage(ProgressDialogHandler.DISMISS_PROGRESS_DIALOG).sendToTarget();
            mHandler = null;
        }
    }


    /**
     * 订阅开始时调用
     * 显示ProgressDialog
     */
    @Override
    public void onStart() {
        super.onStart();
        showProgressDialog();
    }

    @Override
    public void onCompleted() {
        dismissProgressDialog();
    }

    @Override
    public void onError(Throwable e) {
        dismissProgressDialog();
    }

    @Override
    public void onNext(T t) {
    }

    @Override
    public void onCancelProgress() {
        if (isUnsubscribed()) {
            return;
        }
        unsubscribe();
    }
}
